package com.jiangjun.fetch.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jiangjun.fetch.mongo.MongoDBSupport;
import com.jiangjun.fetch.util.Base64;
import com.jiangjun.fetch.util.Page;
import com.jiangjun.fetch.util.ResponseSender;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.util.StringParseUtil;

@WebServlet(name = "GetInfoListServlet", urlPatterns = "/getInfoListService", asyncSupported = false)
@WebInitParam(name = "default_charset", value = "utf-8")
public class GetInfoListServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		/**
		 * 一页取20条
		 */
		String type = request.getParameter("type");// 1是图片，2是文本
		String currentpage = request.getParameter("cpage");
		MongoDBSupport mongoDBSupport = MongoDBSupport.getInstance();
		String collectionName = "";
		if (type.equals("1")) {
			collectionName = MongoDBSupport._FETCHPIC;
		} else if (type.equals("2")) {
			collectionName = MongoDBSupport._FETCHTXT;
		} else if (type.equals("3")) {
			collectionName = MongoDBSupport._FETCHPICLIST;
		}
		Page page = new Page(20, Integer.parseInt(currentpage));
		BasicDBObject sort = new BasicDBObject();
		sort.put("date", -1);
		DBCursor cursor = mongoDBSupport.queryCollectionByParam(collectionName,
				page, null, sort);
		List<DBObject> list = cursor.toArray();
		for (DBObject object : list) {
			if (null != object.get("img_path")) {
				String img_path = object.get("img_path").toString();
				if (img_path.indexOf(";") > -1) {
					StringBuffer sb = new StringBuffer();
					String[] array = img_path.split(";");
					for (String s : array) {
						if (sb.toString().equals("")) {
							sb.append(Start.img_server + s);
						} else {
							sb.append(";");
							sb.append(Start.img_server + s);
						}
					}
					object.put("img_path", sb.toString());
				} else {
					object.put("img_path",
							Start.img_server
									+ object.get("img_path").toString());
				}

			}
			if (null != object.get("txt_path")) {
				String txt_path = Start.txt_server
						+ Base64.encode((object.get("txt_path").toString()).getBytes());
				object.put("txt_path", txt_path);
			}
		}
		String content = list.toString();
		ResponseSender.sendResponse(response, content.getBytes("utf-8"),
				"utf-8", null);
	}
}
